import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { User, UserDocument } from '../entities/user.entity';

@Injectable()
export class UsersService {
  constructor(@InjectModel(User.name) private userModel: Model<UserDocument>) {}

  async create(userData: {
    username: string;
    email: string;
    password: string;
    nickname?: string;
  }): Promise<User> {
    const user = new this.userModel(userData);
    return user.save();
  }

  async findAll(): Promise<User[]> {
    return this.userModel.find().select('-password').exec();
  }

  async findById(id: string): Promise<User | null> {
    return this.userModel.findById(id).select('-password').exec();
  }

  async findByUsername(username: string): Promise<User | null> {
    return this.userModel.findOne({ username }).exec();
  }

  async findByEmail(email: string): Promise<User | null> {
    return this.userModel.findOne({ email }).exec();
  }

  async updateStatus(userId: string, status: string): Promise<User | null> {
    return this.userModel
      .findByIdAndUpdate(userId, { status, lastSeen: new Date() }, { new: true })
      .select('-password')
      .exec();
  }

  async addFriend(userId: string, friendId: string): Promise<User | null> {
    return this.userModel
      .findByIdAndUpdate(
        userId,
        { $addToSet: { friends: friendId } },
        { new: true }
      )
      .select('-password')
      .exec();
  }

  async removeFriend(userId: string, friendId: string): Promise<User | null> {
    return this.userModel
      .findByIdAndUpdate(
        userId,
        { $pull: { friends: friendId } },
        { new: true }
      )
      .select('-password')
      .exec();
  }

  async getFriends(userId: string): Promise<User[]> {
    const user = await this.userModel
      .findById(userId)
      .populate('friends', '-password')
      .exec();
    
    return user?.friends || [];
  }
}
